#include <ulib.h>
#include <file.h>
#include <stat.h>
#include <string.h>
#include <unistd.h>

#define BUFSIZE         4096
#define printf(...)		fprintf(1,__VA_ARGS__)

void
usage(void) {
    printf("usage: diff filename1 filename2\n");
}

void
diff(char* path1, int fd1, char* path2, int fd2) {
    static char buf1[BUFSIZE];
    static char buf2[BUFSIZE];
    int ret1, ret2;
    while ((ret1 = read(fd1, buf1, sizeof(buf1))) > 0) {
        ret2 = read(fd2, buf2, sizeof(buf2));
        if (ret1 != ret2) {
            goto notsame;
        }
        if (strncmp(buf1, buf2, BUFSIZE)) {
            goto notsame;
        }
    }
    if ((ret2 = read(fd2, buf2, sizeof(buf2))) > 0) {
        goto notsame;
    }
    printf("%s and %s is the same\n", path1, path2);
    return;
    
notsame:
    printf("two files different at below:\n");
    printf("%s:\n", path1);
    printf("%s\n", buf1);
    printf("%s:\n", path2);
    printf("%s\n", buf2);
}

int
main(int argc, char** argv) {
    if (argc != 3) {
        usage();
        return -1;
    }
    else {
        int fd1, fd2;
        if ((fd1 = open(argv[1], O_RDONLY)) < 0) {
            printf("open %s failed, exit...\n", argv[1]);
            return fd1;
        }
        if ((fd2 = open(argv[2], O_RDONLY)) < 0) {
            printf("open %s failed, exit...\n", argv[2]);
            return fd2;
        }
        diff(argv[1], fd1, argv[2], fd2);
    }
    return 0;
}
